package com.hwz.gulimall.search.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.hwz.common.to.es.SkuEsModel;
import com.hwz.gulimall.search.constant.EsConstant;
import com.hwz.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: hwz
 * @CreateTime: 2025-07-14
 */

@Service
@Slf4j
public class ProductSaveServiceImp implements ProductSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {

        BulkRequest bulkRequest = new BulkRequest();

        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest request = new IndexRequest(EsConstant.PRODUCT_INDEX);
            request.id(skuEsModel.getSkuId().toString());
            Gson gson = new Gson();
            String json = gson.toJson(skuEsModel);
            request.source(json, XContentType.JSON);
            bulkRequest.add( request);
        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);

        boolean b = bulk.hasFailures();

        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        if (b){
            log.info("商品失败{}",collect);
        }
        return !b;
    }
}
